const fs = require("fs");
const path = require("path");
const http = require("http");

let filePath = path.join(__dirname, "text.txt");
let total = fs.statSync(filePath).size;
let server = http.createServer((req, res) => {
  if (req.url === "/") {
    let range = req.headers["range"];
    if (range) {
      let [, start, end] = range.match(/(\d*)-(\d*)/);
      start = start ? Number(start) : 0;
      end = end ? Number(end) : total - 1;
      res.statusCode = 206;
      res.setHeader("Content-Length", end - start + 1);
      res.setHeader("Content-Range", `bytes ${start}-${end}/${total}`);
      fs.createReadStream(filePath, { start, end }).pipe(res);
    } else {
      fs.createReadStream(filePath).pipe(res);
    }
  } else {
    res.statusCode = 404;
    res.end();
  }
});

server.listen(3000, () => {
  console.log("Server Start");
});
